import { $event } from '/utils'
import { GlobalData } from '/store/state'
import { getServer, isLogin } from '/store/mutations'
import { userApi } from '/api/user'
import { checkAuth } from '/store/actions'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    currencyName: GlobalData.currencyName,
    tabText: ['24时榜', '周榜', '月榜', '同城榜'],
    currTab: 0,
    info: [[] as GetTopicRanksReturn[]],
    list: [[] as GetTopicRanksReturn[]],
    headList: [[] as GetTopicRanksReturn[]],
    self: {} as GetTopicRankReturn,
  },
  async onLoad() {
    if (isLogin()) {
      await this.getInfo()
    } else {
      await checkAuth()
    }
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    this.getPosition()
  },
  getPosition() {
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
    })
  },
  switchTab(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      currTab: e.currentTarget.dataset.id,
    })
    this.getInfo()
  },
  /** 请求排行榜 */
  async getInfo() {
    const id = this.data.currTab
    if (this.data.info[id] && id > 0) return
    const city = wx.getStorageSync(`${getServer()}/logged`).data.location
      ? wx.getStorageSync(`${getServer()}/logged`).data.location.split(' ')[1].replace('市', '')
      : ''
    const data = {
      days: id === 0 ? '1' : id === 1 ? '7' : id === 3 ? '' : '30',
      city: id === 3 ? city : '',
    }
    const list = await userApi.getUserRanks(data)
    this.setData({
      [`info[${id}]`]: list,
      [`headList[${id}]`]: list.rank_list.slice(0, 3),
      [`list[${id}]`]: list.rank_list.slice(3),
      self: list.my_rank,
    })
  },
})
